package com.company.beauty.common.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * <p>长整型序列化转换为字符串类型，避免精度丢失</p>
 *
 * @author youyoukele
 * @version 1.0
 * @date 2022/9/18
 */
public class LongToStringJacksonSerializer extends JsonSerializer<Long> {

    /**
     * Singleton instance to use.
     */
    public final static LongToStringJacksonSerializer instance = new LongToStringJacksonSerializer();

    private static final long MAX_LONG_TO_STRING = (long) Math.pow(10, 15);

    @Override
    public void serialize(Long aLong,
                          JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider)
            throws IOException {
        if (aLong != null) {
            if (aLong > MAX_LONG_TO_STRING) {
                jsonGenerator.writeString(aLong.toString());
            } else {
                jsonGenerator.writeNumber(aLong);
            }
        }
    }
}
